package m

import (
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

// 每日礼包
type DailyGift struct {
	BaseM
	Uid     bson.ObjectId `bson:"_id" json:"_id"`         // 用户uid
	Tid     int64         `bson:"tid" json:"tid"`         // 付费礼包id
	CurTime int64         `bson:"curTime" json:"curTime"` // 当天凌晨时间
	BuyCnt  int64         `bson:"buyCnt" json:"buyCnt"`   // 购买次数
}

func NewDailyGift() cache.EntryI {
	return &DailyGift{}
}

// 保存信息
func (dg *DailyGift) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("DailyGift", bson.M{"_id": dg.Uid}, dg)
	if err != nil {
		return err
	}
	return
}

func (dg *DailyGift) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		dg.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		dg.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "DailyGift_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return dg.LoadData()
}

// 加载数据
func (dg *DailyGift) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("DailyGift", bson.M{"_id": dg.Uid}, nil, &dg)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	return
}

// 更新数据
func (dg *DailyGift) Update(val *DailyGift) {
	Cache.Put("DailyGift", val.Uid.Hex(), val)
	val.UpdateData()
}

// 获取每日礼包信息
func (u *User) GetDailyGift() *DailyGift {
	v, _ := Cache.Get("DailyGift", u.Uid.Hex())
	return v.(*DailyGift)
}
